const express = require('express')

const router = express.Router()

const {db,genid} = require('../db/DbUtils')

const {v4:uuidv4} = require('uuid')

router.post('/login',async (req,res)=>{
    let {account,password} = req.body
    let {err,rows} = await db.async.all('select * from `admin` where `account` = ? AND `password` = ?',[account,password])

    
    if(err == null && rows.length >0){
        //成功

        //生成token
        let login_token = uuidv4();
        //token保存到数据库
        let update_token_sql = 'update `admin` set `token` = ? where `id` = ?'
        
        await db.async.run(update_token_sql,[login_token,rows[0].id])

        //用户数据 (包含token返还前端)
        let admin_info = rows[0]
        admin_info.token = login_token

        //过滤密码
        admin_info.password = '^_^';

        res.send({
            code:200,
            msg:"登录成功",
            data:admin_info
        })
    }else{
        res.send({
            code:500,
            msg:"登录失败"
        })
    }
})
//需要暴露router
module.exports = router